package com.pay.ioopos.support.serialport.custom;

import android.util.Log;
import android.view.KeyEvent;

import com.pay.ioopos.support.serialport.CmdException;
import com.pay.ioopos.support.utils.HexUtil;

/**
 * 串口支付监听
 * @author moyq5
 * @since 2022/7/28
 */
public class SerialPortPayListener implements CustomSerialPortListener {
    private static final String TAG = SerialPortPayListener.class.getSimpleName();
    private static final CustomSerialPortListener listener = new SerialPortPayListener();

    private SerialPortPayListener() {

    }

    public static CustomSerialPortListener getInstance() {
        return listener;
    }

    @Override
    public void onReceive(byte[] bytes) {
        Log.d(TAG, "onReceive: " + HexUtil.toHexString(bytes));
        CustomCmdReceive cmd;
        try {
            cmd = CustomCmdUtils.deserialize(bytes, CustomCmdReceive.class);
        } catch (CmdException e) {
            Log.d(TAG, "onReceive: " + e.getMessage());
            SerialPortPayCmd2KeyEvent eventCmd;
            KeyEvent keyEvent;
            for (int keyCode: SerialPortPayCmd4KeyEventDer.keyCodes) {
                keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);
                eventCmd = new SerialPortPayCmd2KeyEvent(keyEvent);
                Log.d(TAG, "onReceive: " + HexUtil.toHexString(eventCmd.serialize()));
            }
            return;
        }
        if (cmd.getAckType() != CustomCmdAckType.REQ) {
            Log.d(TAG, "onReceive: 非请求指令，忽略");
            return;
        }
        int type = cmd.getCmdType();
        if (type > SerialPortPayCmdType.values().length - 1) {
            Log.d(TAG, "onReceive: 非法指令类型(" +type+ ")");
            return;
        }
        SerialPortPayCmdType cmdType = SerialPortPayCmdType.values()[type];
        cmdType.consume(bytes);
    }

}
